package logic

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"shop_srv/models"

	"shop_srv/internal/svc"
	"shop_srv/shop"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrdersLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrdersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrdersLogic {
	return &CreateOrdersLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateOrdersLogic) CreateOrders(in *shop.CreateOrdersRequest) (*shop.CreateOrdersResponse, error) {
	// todo: add your logic here and delete this line

	var err error
	var g models.Goods
	var o models.Orders

	if err = g.GetGoodsById(in.GoodsId); err != nil {
		logx.Error("获取商品信息失败")
		return nil, errors.New("获取商品信息失败")
	}
	if g.ID == 0 {
		logx.Error("商品不存在")
		return nil, errors.New("商品不存在")
	}
	if g.Stock < in.Num {
		logx.Error("库存不足")
		return nil, errors.New("库存不足")
	}

	o.UserId = in.UserId
	o.GoodsId = in.GoodsId
	o.OrderSn = uuid.NewString()
	o.Num = in.Num
	o.Total = float32(g.Price * float64(in.Num))
	if err = o.CreateOrders(); err != nil {
		logx.Error("订单创建失败")
		return nil, errors.New("订单创建失败")
	}

	g.Stock -= in.Num
	models.DB.Update("stock", g.Stock)

	return &shop.CreateOrdersResponse{
		OrderSn: o.OrderSn,
	}, nil
}
